package util

import (
	"fmt"
	"strconv"
	"time"

	"gitee.com/k-ayaka/et-userserver/po"
	"gitee.com/k-ayaka/std-go/redis"
)

func CacheToken(token string, uid int) {
	_, err := redis.Client.Set(token, uid, 30*time.Minute).Result()
	if err != nil {
		fmt.Println("[Redis]缓存失败", err)
	} else {
		fmt.Println("[Redis]缓存用户登录Token到Redis@" + redis.Client.Options().Addr)
	}
}

func Token2UID(token string) int {
	res, err := redis.Client.Get(token).Result()
	if err != nil {
		fmt.Println("[Redis]Token不存在或已过期")
		return -1
	}
	uid, _ := strconv.Atoi(res)
	return uid
}

func CacheUserInfo(user *po.User) {
	key := strconv.Itoa(int(user.ID))
	userInfo := make(map[string]interface{})
	userInfo["name"] = user.Name
	userInfo["psw"] = user.Password
	userInfo["profile"] = user.Profile
	userInfo["email"] = user.Email
	userInfo["tel"] = user.Tel
	_, err := redis.Client.HMSet(key, userInfo).Result()
	if err != nil {
		fmt.Println("[Redis]缓存失败", err)
	} else {
		redis.Client.Expire(key, 30*time.Minute)
		fmt.Println("[Redis]缓存用户信息到Redis@" + redis.Client.Options().Addr)
	}
}

func GetUserInfo(uid int) *po.User {
	key := strconv.Itoa(uid)
	if !redis.ExistsKey(key) {
		fmt.Println("[Redis]Redis中不存在此用户信息")
		return nil
	}
	userInfo, err := redis.Client.HMGet(key, "name", "psw", "profile", "email", "tel").Result()
	if err != nil {
		fmt.Println("[Redis]获取用户信息失败", err)
	}
	var user po.User
	user.ID = uint(uid)
	user.Name = userInfo[0].(string)
	user.Password = userInfo[1].(string)
	user.Profile = userInfo[2].(string)
	user.Email = userInfo[3].(string)
	user.Tel, _ = strconv.Atoi(userInfo[4].(string))
	return &user
}
